package com.ruikong.dazhi.controller.basicinfo;

import com.github.pagehelper.PageInfo;

import com.ruikong.dazhi.controller.result.BaseResult;
import com.ruikong.dazhi.controller.result.ResultApi;
import com.ruikong.dazhi.entity.basicinfo.Shop;
import com.ruikong.dazhi.model.input.ShopPageInput;
import com.ruikong.dazhi.model.output.PersonnelOutput;
import com.ruikong.dazhi.model.output.ShopPageOutput;
import com.ruikong.dazhi.model.output.TreeMenuOutput;
import com.ruikong.dazhi.service.basicinfo.IDeviceService;
import com.ruikong.dazhi.service.basicinfo.ILineService;
import com.ruikong.dazhi.service.basicinfo.IShopService;
import com.ruikong.dazhi.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (Shop)表控制层
 */
@RestController
@RequestMapping("/data")
@EnableAutoConfiguration
@Api(tags = "车间信息管理")
public class ShopController {

    private static final Logger logger = LoggerFactory.getLogger(ShopController.class);
    /**
     * 车间信息服务对象
     */
    @Autowired
    private IShopService shopService;

    @Autowired
    private ILineService lineService;

    @Autowired
    private IDeviceService deviceService;

    @PostMapping("/getShopById")
    @ApiOperation("根据id获取车间信息")
    public Shop getShopById(@RequestBody Shop shop) {
        return shopService.queryById(shop.getId());
    }

    /**
     * Description: 车间信息分页
     **/
    @PostMapping("/getShopPageList")
    @ApiOperation(value = "车间信息分页")
    public PageInfo<ShopPageOutput> getShopPageList(@RequestBody ShopPageInput input) {
        PageInfo<ShopPageOutput> shopPageOutputPageInfo = new PageInfo<>();
        try {
            shopPageOutputPageInfo = shopService.getShopPageInfo(input);
        } catch (Exception e) {
            logger.error("getRoleListPage{}", e.getMessage());
        }
        return shopPageOutputPageInfo;
    }

    /**
     * Description: 新增车间信息
     *
     * @Param: [shop]
     **/
    @PostMapping("/addShop")
    @ApiOperation("新增车间信息")
    public BaseResult addShop(HttpSession session, HttpServletRequest request, HttpServletResponse response, @RequestBody Shop shop) {
        BaseResult result = new BaseResult();
        try {
            Object object = session.getAttribute("outPersonnel");
            if (object == null) {
                response.sendRedirect(request.getContextPath() + "/view/login");
            }
            PersonnelOutput personnel = (PersonnelOutput) object;
            if (shopService.isExist(shop) > 0) {
                result.setCode(ResultApi.failCode);
                result.setMsg("该车间编号或名称已存在!");
                return result;
            }
            shop.setCreateTime(new Date());
            shop.setUserId(personnel.getPersonnelId());
            shop.setIsDeleted(0);
            shop.setState(1);

            int effect = shopService.insert(shop);
            if (effect > 0) {
                result.setCode(ResultApi.successCode);
                result.setMsg(ResultApi.addSuccessMsg);
            } else {
                result.setCode(ResultApi.failCode);
                result.setMsg(ResultApi.addFailMsg);
            }
        } catch (Exception e) {
            result.setCode(ResultApi.failCode);
            result.setMsg(ResultApi.addFailMsg);
            logger.error("addShop{}", e.getMessage());
        }
        return result;
    }

    /**
     * Description: 更新车间信息
     *
     * @Param: [shop]
     **/
    @PostMapping("/updateShop")
    @ApiOperation("更新车间信息")
    public BaseResult updateShop(@RequestBody Shop shop) {
        BaseResult platformResult = new BaseResult();
        try {
            if (shopService.isExist(shop) > 0) {
                platformResult.setCode(ResultApi.failCode);
                platformResult.setMsg("该车间编号或名称已存在!");
                return platformResult;
            }
            int effect = shopService.update(shop);
            if (effect > 0) {
                platformResult.setCode(ResultApi.successCode);
                platformResult.setMsg(ResultApi.updateSuccessMsg);
            } else {
                platformResult.setCode(ResultApi.failCode);
                platformResult.setMsg(ResultApi.updateFailMsg);
            }
        } catch (Exception e) {
            platformResult.setCode(ResultApi.failCode);
            platformResult.setMsg(ResultApi.updateFailMsg);
            logger.error("updateShop{}", e.getMessage());
        }
        return platformResult;
    }

//    /**
//     * Description: 删除车间信息
//     *
//     * @Param: [shop]
//     **/
//    @PostMapping("deleteShop")
//    @ApiOperation(value = "删除车间信息")
//    public BaseResult deleteShop(@RequestBody Shop shop) {
//        BaseResult platformResult = new BaseResult();
//        try {
//            if (lineService.getLineListByShop(shop.getId()).size() > 0) {
//                platformResult.setCode(ResultApi.failCode);
//                platformResult.setMsg("该车间下有产线,无法删除");
//                return platformResult;
//            }
//            if (deviceService.getDeviceByShop(shop.getId()).size() > 0) {
//                platformResult.setCode(ResultApi.failCode);
//                platformResult.setMsg("该车间下有设备,无法删除");
//                return platformResult;
//            }
//            Integer result = shopService.deleteById(shop.getId());
//            if (result == 1) {
//                platformResult.setMsg(ResultApi.deleteSuccessMsg);
//                platformResult.setCode(ResultApi.successCode);
//            } else {
//                platformResult.setMsg(ResultApi.deleteFailMsg);
//                platformResult.setCode(ResultApi.failCode);
//            }
//        } catch (Exception e) {
//            platformResult.setMsg(ResultApi.deleteFailMsg);
//            platformResult.setCode(ResultApi.failCode);
//            logger.error("deleteShop{}", e.getMessage());
//        }
//        return platformResult;
//    }

    @PostMapping("/getShopTree")
    @ApiOperation(value = "获取所有车间用于Tree展示")
    public List<TreeMenuOutput> getShopTree() {
        List<TreeMenuOutput> list = new ArrayList<>();
        try {
            list = shopService.queryAllTree();
        } catch (Exception e) {
            logger.error("getShopTree{}", e.getMessage());
        }
        return list;
    }

    @PostMapping("/getAllShop")
    @ApiOperation(value = "获取所有车间")
    public BaseResult getAllShop() {
        BaseResult result = new BaseResult();
        try {
            List<Shop> list = shopService.queryAll();
            result.setCode(ResultApi.successCode);
            result.setData(list);

        } catch (Exception e) {
            result.setCode(ResultApi.failCode);
            result.setMsg(ResultApi.getFailMsg);
            logger.error("getAllShop{}", e.getMessage());
        }
        return result;
    }


    @PostMapping("/getShopList")
    @ApiOperation(value = "获取所有可用车间")
    public BaseResult getShopList() {
        BaseResult result = new BaseResult();
        try {
            List<Shop> list = shopService.getAllUsedShop();
            result.setCode(ResultApi.successCode);
            result.setData(list);
        } catch (Exception e) {
            result.setCode(ResultApi.failCode);
            result.setMsg(ResultApi.getFailMsg);
            logger.error("getShopList{}", e.getMessage());
        }
        return result;
    }

    @GetMapping("/downShopExcelTemplate")
    @ApiOperation("车间导出模版下载")
    public void downShopExcelTemplate(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileName") String fileName) {
        String[] columNames = {"车间编号", "车间名称", "车间类型", "创建时间", "创建人", "备注", "状态(正常：1，停用：0)"};
        ExcelUtil.download(response, request, fileName, columNames);
    }

    @PostMapping("/shopImport")
    @ApiOperation("车间信息导入")
    public BaseResult shopImport( @RequestParam("file") MultipartFile multipartFile, HttpSession httpSession){
        PersonnelOutput personnelOutput = (PersonnelOutput) httpSession.getAttribute("outPersonnel");
        int personnelId = personnelOutput.getPersonnelId();
        BaseResult baseResult=new BaseResult();
        try {
            baseResult=this.shopService.shopImport(multipartFile,personnelId);
        }catch (Exception e){
            logger.error("shopImport",e.getMessage());
            e.printStackTrace();
        }
        return baseResult;
    }
}
